package com.powerbank.adminsystem.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powerbank.adminsystem.entity.AdminUser;
import com.powerbank.adminsystem.mapper.AdminUserMapper;
import com.powerbank.adminsystem.service.AdminUserService;
import com.powerbank.common.result.Result;
import com.powerbank.common.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 管理员用户服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser> implements AdminUserService {

    private final AdminUserMapper adminUserMapper;
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    private final JwtUtils jwtUtils;
    
    @Value("${jwt.secret}")
    private String jwtSecret;
    
    @Value("${jwt.expiration}")
    private Long jwtExpiration;

    @Override
    public Result<String> login(String username, String password, String ip) {
        // 根据用户名查询用户
        AdminUser user = adminUserMapper.findByUsername(username);
        if (user == null) {
            return Result.error("用户名或密码错误");
        }

        // 检查用户状态
        if (user.getStatus() != 1) {
            return Result.error("用户已被禁用");
        }

        // 验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            return Result.error("用户名或密码错误");
        }

        // 生成JWT Token
        String token = jwtUtils.generateToken(user.getId(), user.getUsername(), "admin");

        // 更新最后登录信息
        updateLastLoginInfo(user.getId(), ip);

        log.info("管理员登录成功: username={}, ip={}", username, ip);
        return Result.success(token);
    }

    @Override
    public Result<Void> logout(String token) {
        // JWT Token无需特殊处理，客户端删除即可
        log.info("管理员登出成功: token={}", token);
        return Result.success();
    }

    @Override
    public Result<AdminUser> getUserByUsername(String username) {
        AdminUser user = adminUserMapper.findByUsername(username);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 清除密码信息
        user.setPassword(null);
        return Result.success(user);
    }

    @Override
    public Result<AdminUser> getUserByToken(String token) {
        try {
            // 解析JWT Token获取用户ID
            Long userId = jwtUtils.getUserIdFromToken(token);
            
            AdminUser user = getById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }

            // 检查用户状态
            if (user.getStatus() != 1) {
                return Result.error("用户已被禁用");
            }

            // 清除密码信息
            user.setPassword(null);
            return Result.success(user);
        } catch (Exception e) {
            log.error("解析Token失败: token={}", token, e);
            return Result.error("Token无效");
        }
    }

    @Override
    public Result<Void> changePassword(Long userId, String oldPassword, String newPassword) {
        AdminUser user = getById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 验证旧密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            return Result.error("旧密码错误");
        }

        // 更新密码
        user.setPassword(passwordEncoder.encode(newPassword));
        updateById(user);

        log.info("管理员修改密码成功: userId={}", userId);
        return Result.success();
    }

    @Override
    public Result<Void> resetPassword(Long userId) {
        AdminUser user = getById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 重置为默认密码
        String defaultPassword = "powerbank123";
        user.setPassword(passwordEncoder.encode(defaultPassword));
        updateById(user);

        log.info("管理员重置密码成功: userId={}", userId);
        return Result.success();
    }

    @Override
    public Result<Void> updateUserInfo(AdminUser user) {
        AdminUser existingUser = getById(user.getId());
        if (existingUser == null) {
            return Result.error("用户不存在");
        }

        // 更新用户信息
        existingUser.setNickname(user.getNickname());
        existingUser.setEmail(user.getEmail());
        existingUser.setPhone(user.getPhone());
        existingUser.setAvatar(user.getAvatar());
        updateById(existingUser);

        log.info("管理员更新信息成功: userId={}", user.getId());
        return Result.success();
    }

    @Override
    public Result<Void> updateLastLoginInfo(Long userId, String ip) {
        int updated = adminUserMapper.updateLastLoginInfo(userId, LocalDateTime.now(), ip);
        if (updated == 0) {
            return Result.error("更新登录信息失败");
        }

        return Result.success();
    }
}